package com.siemens.industrial.web.mvc.service.partner;

import com.siemens.industrial.utils.DateUtil;
import com.siemens.industrial.utils.JsonToOtherFormat;
import com.siemens.industrial.web.mvc.dao.admin.ChartsDao;
import com.siemens.industrial.web.mvc.dao.partner.PartnerChartsDao;
import com.siemens.industrial.web.mvc.dao.partner.PartnerDeviceShiftRelationDao;
import com.siemens.industrial.web.mvc.dao.partner.PartnerDeviceStatePeriodDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.LoggingMXBean;

/**
 * Created by shuan on 2016/11/15.
 */
@Service
public class PartnerChartsService {
    @Resource
    PartnerChartsDao partnerChartsDao;

    @Resource
    ChartsDao chartsDao;

    @Resource
    PartnerDeviceStatePeriodDao partnerDeviceStatePeriodDao;

    @Resource
    PartnerDeviceStatePeriodService partnerDeviceStatePeriodService;

    @Resource
    PartnerDeviceShiftRelationDao partnerDeviceShiftRelationDao;

    //获取某一机床不同原因的闲置情况(天)
    public Map getSameDeviceDiffTypeTime(String database, String device, String start_time, String end_time) throws ParseException {
        String startTimeString = start_time.replace("/", "-");
        String endTimeString = end_time.replace("/", "-");

        Map map = new HashMap<>();
        List list = new ArrayList<>();
        //获取闲置信息
        List idleInfoList = partnerChartsDao.getSameDeviceDiffTypeTime(database, device, startTimeString, endTimeString);

        if (idleInfoList.size() == 0) {
            return map;
        }

        //获取期间发生闲置的全部原因
        List idLeReasonList = partnerChartsDao.getDeviceIdleReason(database, device, startTimeString, endTimeString);
        if (idleInfoList.size() == 0) {
            return map;
        }

        List reasonList = new ArrayList<>();

        for (int i = 0; i < idLeReasonList.size(); i++) {
            String reasonjson = (String) ((Map) idLeReasonList.get(i)).get("reason");
            reasonList.add(JsonToOtherFormat.buildJsonToMap(reasonjson).get("IDLEReason"));
        }

        for (int i = 0; i < idleInfoList.size(); i++) {
            Map copyMap = new HashMap<>();
            String reasonjson = (String) ((Map) idleInfoList.get(i)).get("meta_definition");
            if (reasonjson == null) {
                copyMap.put("date", ((Map) idleInfoList.get(i)).get("date"));
                list.add(copyMap);
                continue;
            }
            String reason = (String) JsonToOtherFormat.buildJsonToMap(reasonjson).get("IDLEReason");
            if (list != null && list.size() != 0) {
                for (int j = 0; j < list.size(); j++) {
                    if (((Map) list.get(j)).get("date").equals(((Map) idleInfoList.get(i)).get("date"))) {
                        ((Map) list.get(j)).put(reason, ((Map) idleInfoList.get(i)).get("difTime"));
                        break;
                    }
                    if (j == list.size() - 1) {
                        copyMap.put("date", ((Map) idleInfoList.get(i)).get("date"));
                        copyMap.put(reason, ((Map) idleInfoList.get(i)).get("difTime"));
                        list.add(copyMap);
                    }
                }
            } else {
                copyMap.put("date", ((Map) idleInfoList.get(i)).get("date"));
                copyMap.put(reason, ((Map) idleInfoList.get(i)).get("difTime"));
                list.add(copyMap);
            }
        }
        map.put("reasonList", reasonList);
        map.put("idleInfo", list);
        return map;
    }

    //获取某一机床同一原因的闲置情况(天)
    public Map getSameDeviceSameTypeTime(String database, String device, String reason, String reasonName, String start_time, String end_time) throws ParseException {
        String startTime = start_time.replace("/", "-");
        String endTime = end_time.replace("/", "-");

        Map map = new HashMap<>();
        List list = new ArrayList<>();
        List idleInfoList = partnerChartsDao.getSameDeviceSameTypeTime(database, device, reason, startTime, endTime);

        if (idleInfoList.size() == 0) {
            return map;
        }

        for (int i = 0; i < idleInfoList.size(); i++) {
            Map copyMap = new HashMap<>();
            copyMap.put("date", ((Map) idleInfoList.get(i)).get("date"));
            copyMap.put(reasonName, ((Map) idleInfoList.get(i)).get("difTime"));
            list.add(copyMap);
        }

        map.put("device", device);
        map.put("reason", reasonName);
        map.put("idleInfo", list);
        return map;
    }

    //同一原因不同机床的闲置情况
    public Map getSameReasonDevices(String database, String reason, String reasonName, String start_time, String end_time) throws ParseException {
        String startTimeString = start_time.replace("/", "-");
        String endTimeString = end_time.replace("/", "-");

        Map map = new HashMap<>();
        List idleList = new ArrayList<>();

        List deviceInfoList = partnerChartsDao.getSameReasonDeviceTypeTime(database, reason, startTimeString, endTimeString);
        if (deviceInfoList.size() == 0) {
            return map;
        }

        //获取同一原因 发生闲置 的所有机床
        List devices = partnerChartsDao.getSameReasonDevice(database, reason, startTimeString, endTimeString);

        List deviceNames = new ArrayList<>();
        List deviceIds = new ArrayList<>();

        for (int i = 0; i < devices.size(); i++) {
            deviceNames.add(((Map) devices.get(i)).get("device_name"));
            deviceIds.add(((Map) devices.get(i)).get("device_id"));
        }

        for (int i = 0; i < deviceInfoList.size(); i++) {
            Map<String, Object> copyMap = new HashMap<>();
            String date = ((Map) deviceInfoList.get(i)).get("date").toString();
            String deviceName = (String) ((Map) deviceInfoList.get(i)).get("device_name");
            if (deviceName == null) {
                copyMap.put("date", date);
                idleList.add(copyMap);
                continue;
            }
            long difTime = ((BigDecimal) ((Map) deviceInfoList.get(i)).get("difTime")).longValue();
            if (idleList != null && idleList.size() != 0) {
                for (int j = 0; j < idleList.size(); j++) {
                    if (((Map) idleList.get(j)).get("date").equals(date)) {
                        ((Map) idleList.get(j)).put(deviceName, difTime);
                        break;
                    }
                    if (j == idleList.size() - 1) {
                        copyMap.put("date", date);
                        copyMap.put(deviceName, difTime);
                        idleList.add(copyMap);
                    }
                }
            } else {
                copyMap.put("date", date);
                copyMap.put(deviceName, difTime);
                idleList.add(copyMap);
            }
        }

        map.put("idleList", idleList);
        map.put("reason", reasonName);
        map.put("series", deviceNames);
        return map;
    }

    //某班次 某机床 空闲原因 总体情况
    public Map<String, Object> getShiftDeviceFreeInfo(String database, String day, String start_time, String end_time, String device) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        long freeTime = 0;
        String startDay = day;
        if (start_time.compareTo(end_time) > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(day);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            startDay = sdf.format(calendar.getTime());
        }
        List shiftFreeReasonList = partnerChartsDao.getDeviceFreeReason(database, start_time, startDay, day, end_time, device);

        List dataSource = new ArrayList<>();
        if (shiftFreeReasonList.size() == 0) {
            map.put("freeTime", freeTime);
            map.put("dataSource", dataSource);
            return map;
        }

        for (int i = 0; i < shiftFreeReasonList.size(); i++) {
            Map copyMap = new HashMap<>();
            String metaKey = (String) ((Map) shiftFreeReasonList.get(i)).get("meta_key");
            if ("IDLE".equals(metaKey)) {
                String reasonjson = (String) ((Map) shiftFreeReasonList.get(i)).get("meta_definition");
                copyMap.put("reason", JsonToOtherFormat.buildJsonToMap(reasonjson).get("IDLEReason"));
            } else if ("FaultType".equals(metaKey)) {
                String reasonjson = (String) ((Map) shiftFreeReasonList.get(i)).get("meta_definition");
                copyMap.put("reason", JsonToOtherFormat.buildJsonToMap(reasonjson).get("FaultTypeReason"));
            }
            copyMap.put("time", ((Map) shiftFreeReasonList.get(i)).get("time"));
            freeTime += ((BigDecimal) ((Map) shiftFreeReasonList.get(i)).get("time")).longValue();
            dataSource.add(copyMap);
        }

        map.put("freeTime", freeTime);
        map.put("dataSource", dataSource);
        return map;
    }

    //获取全部idle原因
    public List getIdleReasons(String database) {
        List idleReasons = partnerChartsDao.getIdleReasons(database);

        List<Map<String, Object>> list = jsonIdleToMap(idleReasons);
        return list;
    }

    //获取全部faultType原因
    public List getFaultType(String database) {
        List list = new ArrayList<>();
        List faultTypes = partnerChartsDao.getFaultType(database);

        for (int i = 0; i < faultTypes.size(); i++) {
            Map map = new HashMap<>();
            String reasonJosn = ((Map) faultTypes.get(i)).get("meta_definition").toString();
            String faultType = JsonToOtherFormat.buildJsonToMap(reasonJosn).get("FaultTypeReason").toString();
            map.put("faultType", faultType);
            map.put("faultId", ((Map) faultTypes.get(i)).get("meta_id"));
            list.add(map);
        }
        return list;
    }

    //shift oee 对比 一段时间(oee=availability) 小时显示
    public List<Map<String, Object>> serviceShiftCompareNew(String database, String[] deviceIdArr, String day, String type) throws ParseException {
        List<Map<String, Object>> serviceList = new ArrayList<>();

        //查询某服务 日期是否在服务期限内
        List<Map<String, Object>> isInRange = chartsDao.findDayTenantServiceStateByType(database, day, type);
        if (isInRange.size() == 0 || Integer.parseInt(isInRange.get(0).get("inrange").toString()) != 1) {
            return serviceList;
        }
        serviceList = partnerChartsDao.findShiftServiceByNew(database, deviceIdArr, day);

        return serviceList;
    }

    //获取机床根据机床类型和机床型号
    public List getDevicesByModelAndType(String database, String type, String model) {
        return partnerChartsDao.findDevicesByModelAndType(database, type, model);
    }

    //oee 对比 一段时间(oee=availability)
    public Map<String, Object> serviceCompareNew(String tenantId, String[] deviceIdArr, String startTime, String endTime, String type) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> serviceState = chartsDao.findTenantServiceState(tenantId, startTime, endTime, type);
        if (serviceState.size() == 0) {
            return map;
        } else if (serviceState.get(0).get("startTime") == null || serviceState.get(0).get("endTime") == null) {
            map.put("serviceData", null);
            map.put("serviceState", serviceState);
            return map;
        }
        List<Map<String, Object>> serviceList = partnerChartsDao.findDataForServiceCompareNew(tenantId, deviceIdArr, serviceState.get(0).get("startTime").toString(), serviceState.get(0).get("endTime").toString());
        map.put("serviceData", serviceList);
        map.put("serviceState", serviceState);
        return map;
    }

    //获取设备发生过的idle原因
    public List<Map<String, Object>> getIdleReasonByDevice(String database, String deviceId) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> idleReasons = partnerChartsDao.findIdleReasonByDevice(database, deviceId);
        if (idleReasons.size() != 0) {
            list = jsonIdleToMap(idleReasons);
            return list;
        }
        return list;
    }

    //获取：最近的系统性能参数
    public Map<String, Object> getRecentlyIndexParam(String database, String deviceId, String day) {
        //判断是否在服务期间
        List<Map<String, Object>> isInRange = chartsDao.findDayTenantServiceState(database, day);
        if (isInRange.size() == 0) {
            return new HashMap<>();
        }
        List<Map<String, Object>> recentlyIndexParam = partnerChartsDao.findRecentlyIndexParam(database, deviceId, day);
        if (recentlyIndexParam.size() == 0) {
            return new HashMap<>();
        }
        for (int i = 0; i < isInRange.size(); i++) {
            if (Integer.parseInt(isInRange.get(i).get("inrange").toString()) == 0) {
                recentlyIndexParam.get(0).put(isInRange.get(i).get("service_name").toString().toLowerCase(), null);
            }
        }
        return recentlyIndexParam.get(0);
    }

    //获取：机床某天工作状态
    public List<Map<String, Object>> getWorkStatusPie(String database, String day, String deviceId) {
        return partnerChartsDao.findWorkStatus(database, day, deviceId);
    }

    //获取：机床某天工作状态   通过代码
    public List<Map<String, Object>> getWorkStatusPieByCalculate(String database, String deviceId, String day) throws ParseException {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> periodTimes = partnerDeviceStatePeriodService.getPeriodsoftimeByCalculate(database, deviceId, day);

        Map<String, Object> planDowntime = new HashMap<String, Object>() {{
            put("device_id", deviceId);
            put("state", "计划停机");
            put("time", 0);
        }};
        Map<String, Object> idle = new HashMap<String, Object>() {{
            put("device_id", deviceId);
            put("state", "idle");
            put("time", 0);
        }};
        Map<String, Object> working = new HashMap<String, Object>() {{
            put("device_id", deviceId);
            put("state", "正常");
            put("time", 0);
        }};

        for (Map<String, Object> periodTime : periodTimes) {
            int state = Integer.parseInt(periodTime.get("state").toString());
            int minute = Integer.parseInt(periodTime.get("minute").toString());
            if (state == -1) {
                int timeCount = Integer.parseInt(planDowntime.get("time").toString()) + minute;
                planDowntime.put("time", timeCount);
            }
            if (state == 0) {
                int timeCount = Integer.parseInt(idle.get("time").toString()) + minute;
                idle.put("time", timeCount);
            }
            if (state == 1) {
                int timeCount = Integer.parseInt(working.get("time").toString()) + minute;
                working.put("time", timeCount);
            }
        }
        if (!planDowntime.get("time").equals(0)) {
            resultList.add(planDowntime);
        }
        if (!idle.get("time").equals(0)) {
            resultList.add(idle);
        }
        if (!working.get("time").equals(0)) {
            resultList.add(working);
        }
        return resultList;
    }

    //获取数据：某天idle原因的分布
    public List<Map<String, Object>> getDayIdleReason(String database, String day, String deviceId) {
        List<Map<String, Object>> idleReasons = partnerChartsDao.findDayIdleReason(database, day, deviceId);
        if (idleReasons.size() == 0) {
            return idleReasons;
        }
        for (int i = 0; i < idleReasons.size(); i++) {
            String reasonjson = (String) idleReasons.get(i).get("meta_definition");
            String idleReason = (String) JsonToOtherFormat.buildJsonToMap(reasonjson).get("IDLEReason");
            idleReasons.get(i).put("idle", idleReason);
        }
        return idleReasons;
    }

    //idle json--map
    public List<Map<String, Object>> jsonIdleToMap(List<Map<String, Object>> idleReasons) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < idleReasons.size(); i++) {
            Map map = new HashMap<>();
            String reasonjson = (String) ((Map) idleReasons.get(i)).get("meta_definition");
            String idleReason = (String) JsonToOtherFormat.buildJsonToMap(reasonjson).get("IDLEReason");
            map.put("idleName", idleReason);
            map.put("idleId", ((Map) idleReasons.get(i)).get("meta_id"));
            list.add(map);
        }
        return list;
    }


    public List<Map<String, Object>> getTimePeriod(String tenantId, String date, String deviceId) throws ParseException {
        List<Map<String, Object>> maps = partnerChartsDao.getTimePeriod(tenantId, date, deviceId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> times = new ArrayList<>();
        for (int i = 0; i < maps.size(); i++) {
            String failureStartTime = maps.get(i).get("start_time").toString();
            String repair = maps.get(i).get("repair_info").toString();
            Map<String, Object> repairMap = JsonToOtherFormat.buildJsonToMap(repair);
            String repairStart = repairMap.get("startTime").toString();
            long failureStartTimeL = sdf.parse(failureStartTime).getTime();
            long repairStartTimeL = sdf.parse(repairStart).getTime();
            Map<String, Object> map = new HashMap<>();
            map.put("failureStartTime", failureStartTimeL);
            map.put("repairStartTime", repairStartTimeL);
            map.put("failureInfo", repairMap.get("faultReason") + ":failure Start");
            map.put("repairInfo", repairMap.get("faultReason") + ":Repair Start");
            map.put("zero", getZero(sdf.parse(date)));
            times.add(map);
        }
        return times;
    }

    public static long getZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    private long getZero() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis();
    }

    public List<Map<String, Object>> getDownTimeTable(String database, String date, String deviceId) throws ParseException {
        List<Map<String, Object>> list = partnerChartsDao.getDashboredOtherByDay(database, date, deviceId);
        if (list.size() == 0)
            return list;
        List<Map<String, Object>> maps = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            Map<String, Object> repairMap = JsonToOtherFormat.buildJsonToMap(map.get("repair_info").toString());
            Map<String, Object> metaMap = JsonToOtherFormat.buildJsonToMap(map.get("meta_definition").toString());
            Map<String, Object> mt = this.getDownTimeMBTROfWeek(database, map.get("start_time").toString(), deviceId, map.get("idle_reason").toString(), false);
            map.put("repairStartTime", repairMap.get("startTime"));
            map.put("repairEndTime", repairMap.get("endTime"));
            map.put("repairPerson", repairMap.get("maintainUser"));
            map.put("reason", repairMap.get("faultReason"));
            map.put("faultMode", metaMap.get("FaultTypeReason"));
            map.put("mttr", mt.get("mttr"));
            map.put("mtbf", mt.get("mtbf"));
            maps.add(map);
        }
        return maps;
    }

    //获取downtime 时间线
    public Map<String, Object> getDownTimeMBTROfWeek(String database, String date, String deviceId, String meta_id, Boolean istrue) throws ParseException {
        String time = date;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date formatDate = format.parse(time);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(formatDate);
        calendar.add(Calendar.DATE, -7);
        String startDate = format.format(calendar.getTime());
        String endDate = format.format(formatDate);
        List<Map<String, Object>> allData = partnerChartsDao.getDashboredOtherMTTRAndMTBF(database, deviceId, meta_id, endDate, startDate);
        //平局故障间隔时间
        List<Long> mttrs = new ArrayList<>();
        //平均修复时间
        List<Long> mtbrs = new ArrayList<>();
        Date endTime = null;
        for (int i = 0; i < allData.size(); i++) {
            Map<String, Object> thismap = allData.get(i);
            if (endTime == null) {
                endTime = format.parse(thismap.get("end_time").toString());
            } else {
                mttrs.add(format.parse(thismap.get("end_time").toString()).getTime() - endTime.getTime());
            }

            Map<String, Object> repairMap = JsonToOtherFormat.buildJsonToMap(thismap.get("repair_info").toString());
            String repairStartTime = repairMap.get("startTime").toString();
            String repairEndTime = repairMap.get("endTime").toString();
            mtbrs.add(format.parse(repairEndTime).getTime() - format.parse(repairStartTime).getTime());
            //mtbf 平均故障间隔时间  这次结束 到 下次开始 为 故障间隔 出现的次数
            //mttr 平均恢复时间     一次repair info 开始 到结束 为 恢复时间 的;
        }
        long mttr = getAverage(mttrs) / (1000 * 60);
        long mtbf = getAverage(mtbrs) / (1000 * 3600);
        if (istrue) {
            //mtbr 平均修理时间间隔
            //mttr 平均修理时间
        }
        return new HashMap<String, Object>() {{
            put("mttr", mttr);
            put("mtbf", mtbf);
        }};
    }

    //获取数据：
    public Map<String, Object> getDownTimeAverageMTBRAndMTTRChart(String database, String date, String deviceId, String idleReason) throws ParseException {
        date = date + " 00:00:00";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date formatDate = format.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(formatDate);
        calendar.add(Calendar.DATE, -7);
        String startDate = format.format(calendar.getTime());
        String endDate = format.format(formatDate);
        List<Map<String, Object>> allData = partnerChartsDao.getAllData(database, deviceId, idleReason, endDate, startDate);
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < allData.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> dataMap = allData.get(i);
            map.put("day", dataMap.get("date_id"));
            if (dataMap.get("repair") == null) {
                map.put("repair", 0);
            } else {
                String repairString = "[" + dataMap.get("repair").toString() + "]";
                List<Map<String, Object>> maps = JsonToOtherFormat.buildJsonToMaps(repairString);
                long sum = 0;
                for (int j = 0; j < maps.size(); j++) {
                    Map<String, Object> repair = maps.get(j);
                    long one = format.parse(repair.get("endTime").toString()).getTime() - format.parse(repair.get("startTime").toString()).getTime();
                    sum += one;
                }
                map.put("repair", sum / (maps.size() * 1000 * 3600));
            }
            list.add(map);
        }
        Map<String, Object> series = new HashMap<String, Object>() {{
            put("argumentField", "day");
            put("valueField", "repair");
            put("name", "MTTR(Hours)");
            put("type", "bar");
            put("color", "#ffaa66");
        }};
        return new HashMap<String, Object>() {{
            put("mttrDataSource", list);
            put("mttrSeries", series);
            put("mtbrDataSource", null);
            put("mtbrSeries", null);
        }};
    }


    private long getAverage(List<Long> list) {
        long sum = 0;
        for (long s : list) {
            sum += s;
        }
        return list.size() == 0 ? 0 : sum / list.size();
    }

    public Map<String, Object> downTimeDataOfPie(String tenantId, String deviceId, String endTime, String startTime) {
        List<Map<String, Object>> list = partnerChartsDao.getWeekDownTimePieChartData(tenantId, deviceId, endTime, startTime);
        List<Map<String, Object>> dataSource = new ArrayList<>();
        int sum = 0;
        Map<String, Object> idleReason = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> dataMap = list.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("metaId", dataMap.get("meta_id"));
            map.put("time", dataMap.get("timePeriod"));
            idleReason.put(dataMap.get("meta_id").toString(), dataMap.get("meta_definition"));
            dataSource.add(map);
            sum += Integer.parseInt(dataMap.get("timePeriod").toString());
        }
        final int finalSum = sum;
        return new HashMap<String, Object>() {{
            put("sum", finalSum);
            put("dataSource", dataSource);
            put("reason", idleReason);
        }};
    }

    public Map<String, Object> downTimeDataOfBar(String tenantId, String deviceId, String endTime, String startTime) {
        List<Map<String, Object>> list = partnerChartsDao.getWeekDownTimeBarChartData(tenantId, deviceId, endTime, startTime);
        List<Map<String, Object>> dataSource = new ArrayList<>();
        List<Map<String, Object>> series = new ArrayList<>();
        for (Map map : list) {
            Map<String, Object> mapSource = new HashMap<>();
            mapSource.put("date_id", map.get("date_id"));
            if (map.get("idle_reason") != null) {
                Map<String, Object> mapSeries = new HashMap<>();
                mapSource.put(map.get("idle_reason").toString(), map.get("timePeriod"));
                mapSeries.put("valueField", map.get("idle_reason"));
                Map<String, Object> definition = JsonToOtherFormat.buildJsonToMap(map.get("meta_definition").toString());
                if (definition.containsKey("IDLEReason")) {
                    mapSeries.put("valueField", map.get("idle_reason"));
                    mapSeries.put("name", definition.get("IDLEReason"));
                    if (!series.contains(mapSeries)) {
                        series.add(mapSeries);
                    }
                } else {
                    mapSeries.put("valueField", map.get("idle_reason"));
                    mapSeries.put("name", definition.get("FaultTypeReason"));
                    if (!series.contains(mapSeries)) {
                        series.add(mapSeries);
                    }
                }
            }
            dataSource.add(mapSource);
        }

        return new HashMap<String, Object>() {{
            put("dataSource", dataSource);
            put("series", series);
        }};
    }

    //oee 对比 一段时间(原 可选)
    public List<Map<String, Object>> serviceCompare(String tenantId, String[] deviceIdArr, String startTime, String endTime) throws ParseException {
        String param = "";
        String startTimeString = startTime.replace("/", "-");
        String endTimeString = endTime.replace("/", "-");
        for (int i = 0; i < deviceIdArr.length; i++) {
            if (i == 0) {
                param += "select `date_id`,'" + deviceIdArr[i] + "' device_id from `" + tenantId + "`.v_num WHERE date_id BETWEEN date('" + startTimeString + "') AND date('" + endTimeString + "')";
            } else {
                param += " union all select `date_id`,'" + deviceIdArr[i] + "' device_id from `" + tenantId + "`.v_num WHERE date_id BETWEEN date('" + startTimeString + "') AND date('" + endTimeString + "')";
            }
        }

        String selectSql = "select d.*,a.device_unique_id as deviceName, ifnull(k.availability,0) availability,ifnull(k.performance,0) performance,ifnull(k.quality,0) quality, ifnull(k.oee,0) oee from \n" +
                "(" + param + ") d\n" +
                "left join (SELECT * FROM `" + tenantId + "`.device_kpi) k\n" +
                "on d.date_id=k.date_Id\n" +
                "and d.device_id=k.device_id left join\n" +
                "        `" + tenantId + "`.device a on a.device_id = d.device_id order by date_id;";

        return partnerChartsDao.getDataforServiceCompare(selectSql);
    }

    public List<Map<String, Object>> otherTimeLine(String tenantId, String deviceId, String day, List<Map<String, Object>> listMap) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Map<String, Object> map : listMap) {

            String title = map.get("title").toString();
            int statusType = Integer.parseInt(map.get("statusType").toString());
            int stType = Integer.parseInt(map.get("stType").toString());
            List<Map<String, Object>> list = partnerChartsDao.getOtherPeriodLine(tenantId, day, statusType, deviceId);

            mapList.add(new HashMap<String, Object>() {{
                put("typeTimePeriod", list);
                put("type", statusType);
                put("title", title);
                put("stType", stType);
            }});
        }
        GregorianCalendar x = new GregorianCalendar();
        x.setTime(new Date());
        return mapList;
    }

    public List<Map<String, Object>> splitShift(String tenantId, String day) {
        List<Map<String, Object>> shiftsOfDay = partnerDeviceShiftRelationDao.getShiftListByDay(tenantId, day);
        List<Map<String, Object>> mapList = new ArrayList<>();
        try {
            Date today = DateUtil.stringFormateDate(day);
            Date tomorrow = DateUtil.lessOrAddDay(today, +1);
            for (Map<String, Object> map : shiftsOfDay) {
                String start = map.get("start_time").toString().substring(0, 2);
                String end = map.get("end_time").toString().substring(0, 2);
                if (Integer.parseInt(start) < Integer.parseInt(end)) {
                    Map<String, Object> otherMap = new HashMap<>();
                    otherMap.put("start_time", day + " " + start + ":00:00");
                    otherMap.put("end_time", DateUtil.dateFormateString(tomorrow) + " " + "00:00:00");
                    mapList.add(otherMap);
                } else {
                    Map<String, Object> splitTwo = new HashMap<>();
                    splitTwo.put("start_time", DateUtil.dateFormateString(tomorrow) + " " + "00:00:00");
                    splitTwo.put("end_time", DateUtil.dateFormateString(tomorrow) + " " + end + ":00:00");
                    mapList.add(splitTwo);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return mapList;
    }
}
